#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Author          : ricsy
@File            : sphinx_bilibili.py
@Create Time     : 2025/6/10 10:21
@Last Modified   :
@Description     : bilibili 插件（https://player.bilibili.com/）
"""
from docutils import nodes
from docutils.parsers.rst import Directive
from docutils.parsers.rst.directives import flag, unchanged


class BilibiliDirective(Directive):
    required_arguments = 1
    optional_arguments = 0
    final_argument_whitespace = True
    option_spec = {
        "width": unchanged,  # 视频宽度
        "height": unchanged,  # 视频高度
        "poster": flag,  # 展示封面
        "autoplay": flag,  # 自动播放
        "muted": flag,  # 静音
        "danmaku": flag,  # 关闭弹幕
    }

    DEFAULT_OPTIONS = {
        "width": "100%",
        "height": "450px",
        "poster": 1,
        "autoplay": 0,
        "muted": 1,
        "danmaku": 1,
    }

    def run(self):
        bvid = self.arguments[0]
        options = {**self.DEFAULT_OPTIONS, **self.options}

        html = f"""
        <iframe 
            src="//player.bilibili.com/player.html?bvid={bvid}&poster={options["poster"]}&autoplay={options["autoplay"]}&danmaku={options["danmaku"]}"
            width="{options["width"]}"
            height="{options["height"]}"
            scrolling="no"
            border="0"
            frameborder="no"
            framespacing="no"
            allowfullscreen="true">
        </iframe>
        """
        return [nodes.raw("", html, format="html")]


def setup(app):
    app.add_directive("bilibili", BilibiliDirective)
